//
//  PhotoBrowserController.swift
//  JKDWeiBoExercise
//
//  Created by 简康达 on 16/6/23.
//  Copyright © 2016年 JKD. All rights reserved.
//

import UIKit
import SnapKit
import SVProgressHUD
private let PhotoBrowserCellID = "PhotoBrowserCellID"
class PhotoBrowserController: UIViewController {
//   MARK:- 属性
    private var indexPath : NSIndexPath
    private var picURLs : [NSURL]
//    MARK:- 懒加载属性
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserCollectionViewLayout())
    private lazy var closeBtn : UIButton = UIButton(title: "关 闭", backgroundColor: UIColor.grayColor(), fontSize: 14)
    private lazy var saveBtn : UIButton = UIButton(title: "保 存", backgroundColor: UIColor.grayColor(), fontSize: 14)
//    重写构造函数
    init(indexPath:NSIndexPath,picURLs:[NSURL]){
        self.indexPath = indexPath
        self.picURLs = picURLs
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func loadView() {
        super.loadView()
        view.frame.size.width += 15
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.orangeColor()
//        设置UI界面
        setupUI()
//        滚动到相应图片的位置
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
    }
}
//MARK:- UI相关设置
extension PhotoBrowserController{
    func setupUI() {
//        添加子控件
        view.addSubview(collectionView)
        view.addSubview(closeBtn)
        view.addSubview(saveBtn)
        collectionView.dataSource = self
        collectionView.frame = view.bounds
//        注册cell
        collectionView.registerClass(PhotoBrowserViewCell.self, forCellWithReuseIdentifier: PhotoBrowserCellID)
//        添加约束
        closeBtn.snp_makeConstraints { (make) in
            make.left.equalTo(20)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 90, height: 32))
        }
        saveBtn.snp_makeConstraints { (make) in
            make.right.equalTo(-20)
            make.bottom.equalTo(-20)
            make.size.equalTo(CGSize(width: 90, height: 32))
        }
//        监听按钮的点击
        closeBtn.addTarget(self, action: #selector(PhotoBrowserController.closeBtnClick), forControlEvents: .TouchUpInside)
        saveBtn.addTarget(self, action: #selector(PhotoBrowserController.saveBtnClick), forControlEvents: .TouchUpInside)
        
    }
}
//MARK:- 实现数据源代理方法
extension PhotoBrowserController : UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picURLs.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserCellID, forIndexPath: indexPath) as! PhotoBrowserViewCell
//        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.blueColor() : UIColor.redColor()
        cell.picURL = picURLs[indexPath.row]
        cell.delegate = self
        return cell
    }
}
//MARK:- 代理方法的实现
extension PhotoBrowserController : PhotoBrowserViewCellDelegate{
    func iamgeViewClickForCell(cell: PhotoBrowserViewCell) {
        closeBtnClick()
    }
}
extension PhotoBrowserController : PhotoBrowserDismissDelegate{
    func imageViewForDismissView() -> UIImageView {
        let imageView = UIImageView()
//        取出图片
        let cell = collectionView.visibleCells().first as! PhotoBrowserViewCell
        let image = cell.imageView.image!
        imageView.image = image
        //        计算图片方法后的位置
        let x : CGFloat = 0
        let width = UIScreen.mainScreen().bounds.width
        let height = UIScreen.mainScreen().bounds.width / image.size.width * image.size.height
        var y = (UIScreen.mainScreen().bounds.height - height) * 0.5
        y = y < 0 ? 0 : y
        let rect : CGRect = CGRect(x: x, y: y, width: width, height: height)
        imageView.frame = rect
//        设置imageView的属性
        imageView.clipsToBounds = true
        imageView.contentMode = .ScaleAspectFill
        return imageView
    }
    func indexPathForDismissView() -> NSIndexPath {
        let cell = collectionView.visibleCells().first!
        return collectionView.indexPathForCell(cell)!
    }
}
//MARK:- 监听事件
extension PhotoBrowserController{
    @objc private func closeBtnClick(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    @objc private func saveBtnClick(){
//        取出当前的cell
        let cell = collectionView.visibleCells().first as! PhotoBrowserViewCell
//        取出当前cell显示的图片
        guard let image = cell.imageView.image else{
            return
        }
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(PhotoBrowserController.isImageSaveSuccess(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    @objc private func isImageSaveSuccess(image:UIImage,didFinishSavingWithError:NSError?,contextInfo:AnyObject){
        let message = didFinishSavingWithError != nil ? "保存失败" : "保存成功"
        SVProgressHUD.showInfoWithStatus(message)
    }
}
//自定义colletionView布局
class PhotoBrowserCollectionViewLayout : UICollectionViewFlowLayout{
    override func prepareLayout() {
//    1.布局设置
        itemSize = collectionView!.bounds.size
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .Horizontal
//        2.collectionView相关设置
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
    }
}
